package com.example.day12;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//读写锁
public class ReadWriteLock {
    //缓存,读写操作的都是这个数据
    //private volatile Map<String,Object> maps = new HashMap<>();

    //定义一个读写锁
    private ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock();

    //获取读锁
    private Lock rlock= rwlock.readLock();

    //获取写锁
    private Lock wlock=rwlock.writeLock();

    public  void write(){
        try {
            wlock.lock();
            System.out.println(Thread.currentThread().getName()+"写线程enter！");
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"写线程leave！");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            wlock.unlock();
        }
    }

    public  void  read(){
            try {
             rlock.lock();
                System.out.println(Thread.currentThread().getName()+"读线程enter！");
                TimeUnit.SECONDS.sleep(1);
                System.out.println(Thread.currentThread().getName()+"读线程leave！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                rlock.unlock();
            }
    }
}
class  tableDemoTest{
    public static void main(String[] args) {
        ReadWriteLock t=new ReadWriteLock();
        for (int i=0;i<5;i++){
            new  Thread(()->t.write()).start();
        }
    }
}
